<?php
/**
 * Created by PhpStorm.
 * User: qinkai
 * Date: 2019/5/13
 * Time: 11:00
 * Email: qinkai@ucex.pro
 */

namespace app\traits;

trait Until
{
    //生成token
    public static function createToken($user_id, $lifetime = 86400)
    {
        $s_user  = sprintf('%08x', $user_id);
        $s_death = sprintf('%08x', $lifetime + time());
        $s_seed  = $user_id;
        $s_hash1 = sprintf('%08x', crc32($s_user . $s_seed . $s_death));
        $s_hash2 = sprintf('%08x', crc32($s_death . $s_seed . $s_user));
        return $s_hash1 .
            substr($s_user, 4) .
            substr($s_hash2, 0, 4) .
            substr($s_user, 0, 4) .
            substr($s_hash2, 4) .
            $s_death;
    }


    //解密token
    public static function parse($token)
    {
        if (!preg_match('/^[\da-f]{32}$/', $token)) {
            $data = ['code' => '1002019', 'msg' => 'token非法', 'data' => null];
        }
        $s_user  = substr($token, 16, 4) . substr($token, 8, 4);
        $s_death = substr($token, 24);
    }

    //生成随机字符串
    public static function strRandom($length = 6)
    {
        $code = "ABCDEFGHIGKLMNOPQRSTUVWXYZ";
        $rand = $code[rand(0, 25)] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        for ($a = md5($rand, true),
             $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV',
             $d = '',
             $f = 0;
             $f < $length;
             $g = ord($a[$f]), // ord（）函数获取首字母的 的 ASCII值
             $d .= $s[($g ^ ord($a[$f + 8])) - $g & 0x1F],//按位亦或，按位与。
             $f++
        ) ;
        return $d;
    }


}
